﻿using AutoMapper;
using MediatR;
using MyMES.Domain.yjb;
using MyMES.Error;
using MyMES.Infrastructure.Interface;
using MyMES.Writer.API.Application.Commends.settingCommand;
using MyMES.Writer.API.FileNlog;

namespace MyMES.Writer.API.Application.CommendHandlers.settingCommand
{
    public class ProcessInfoCommandHandlers : IRequestHandler<ProcessInfoCommand, APIResult<ProcessInfo>>
    {
        private readonly IBaseRepository<ProcessInfo> accreop;
        private readonly IMapper mapper;
        private readonly Nolgs nolgs;

        public ProcessInfoCommandHandlers(IBaseRepository<ProcessInfo> accreop, IMapper mapper,Nolgs nolgs)
        {
            this.accreop = accreop;
            this.mapper = mapper;
            this.nolgs = nolgs;
        }
        /// <summary>
        /// 生产-添加
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<APIResult<ProcessInfo>> Handle(ProcessInfoCommand request, CancellationToken cancellationToken)
        {
            var startTime= DateTime.Now;
            try
            {
                APIResult<ProcessInfo> result = new APIResult<ProcessInfo>();
                result.Code = APIEnum.添加成功;
                result.Msg = "添加成功";
                var model = mapper.Map<ProcessInfo>(request);
                string sql = "insert into ProcessInfo(processInfoId,processCode, processName, isEnabled, processDescription, remarks, operationStepInfoId,isDelete) values(@processInfoId,@processCode, @processName, @isEnabled, @processDescription, @remarks, @operationStepInfoId, @isDelete)";
                await accreop.Insert(model, sql);
                return result;
            }
            catch (Exception)
            {

                throw;
            }
            finally
            {
                var endTime = System.DateTime.Now;

                var durationInDays = (endTime - startTime).Days;
                nolgs.GetNlogs(
                    request.ProcessName ?? "Unknow", "工序添加", "False", durationInDays, "异常信息"
                    );
            }
        }
    }
}
